<template>
  <div class="execution">
      <el-form inline :model="dataForm" v-if="searchFormShow">
        <el-row class="bg-row">
          <el-col :span="24">
            <el-form-item label="学校区域">
              <el-form-item label-width="0">
                <el-select v-model="dataForm.provinceCode" filterable default-first-option clearable @change="getCityOptions">
                  <el-option v-for="item in provinceOptions" :value="item.id" :label="item.regionName" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="0">
                <el-select v-model="dataForm.cityCode" filterable default-first-option clearable @change="getAreaOptions">
                  <el-option v-for="item in cityOptions" :value="item.id" :label="item.regionName" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="0">
                <el-select v-model="dataForm.areaCode" filterable default-first-option clearable>
                  <el-option v-for="item in areaOptions" :value="item.id" :label="item.regionName" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="bg-row">
          <el-col :span="24">
            <el-form-item label="学年">
              <el-col :span="11">
                <el-date-picker v-model="dataForm.fromYear" type="year" value-format="yyyy" placeholder="选择年"></el-date-picker>
              </el-col>
              <el-col :span="2" style="text-align: center;">至</el-col>
              <el-col :span="11">
                <el-date-picker v-model="dataForm.toYear" type="year" value-format="yyyy" placeholder="选择年"></el-date-picker>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="bg-row">
          <el-col :span="24">
            <el-form-item label="学校类型">
              <el-select v-model="dataForm.schoolType" @change="schoolTypeChangeHandle" clearable>
                <el-option v-for="item in typeOptions" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="学校班级">
              <el-form-item label-width="0">
                <el-select filterable default-first-option clearable v-model="dataForm.schoolId" @change="getGradeOption">
                  <el-option v-for="item in schoolOptions" :value="item.id" :label="item.schoolName" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="0">
                <el-select filterable default-first-option clearable v-model="dataForm.gradeId" @change="getClassOption">
                  <el-option v-for="item in gradeOptions" :value="item.id" :label="item.gradeName" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="0">
                <el-select filterable default-first-option clearable v-model="dataForm.classId">
                  <el-option v-for="item in classOptions" :value="item.id" :label="item.className" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-form-item>
            <el-form-item label="登记状态">
              <el-select v-model="dataForm.reportStatus">
                <el-option label="登记" :value="1"></el-option>
                <el-option label="未登记" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="bg-row">
          <el-col :span="6">
            <el-form-item label="学生学号">
              <el-input v-model="dataForm.sno"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="学生名称">
              <el-input v-model="dataForm.studentName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="dataForm.status">
                <el-option v-for="item in statusOptions" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="searchHandle">查询</el-button>
              <el-button icon="el-icon-delete" type="info" @click="clearSearchForm">清空</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="margin-top: 5px;margin-bottom: 5px;">
        <el-row style="margin-top: 5px;">
          <el-button v-if="permissions.admin_student_add" icon="el-icon-plus" type="primary" @click="addOrUpdateHandle('','add')">新增</el-button>
          <el-button v-if="permissions.admin_student_add" icon="el-icon-upload" type="primary" @click="importExcel()">导入Excel</el-button>
          <el-button  icon="el-icon-printer" type="primary" @click="printInfo()">导出成Excel</el-button>
          <el-tooltip class="item" effect="dark" content="搜索" placement="top" style="float: right;">
            <el-button icon="el-icon-search" circle @click="searchFormShow = !searchFormShow"></el-button>
          </el-tooltip>
        </el-row>
      </div>

      <el-table :data="dataList" height="calc(100vh - 215px)" border stripe v-loading="dataListLoading">
        <el-table-column prop="studentName" label="学生姓名" width="100">
          <template slot-scope="scope">
            <el-button v-if="permissions.admin_student_edit" type="text" @click="addOrUpdateHandle(scope.row.id,'edit')">{{scope.row.studentName}}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="birthDay" label="出生年月" width="120"></el-table-column>
        <el-table-column prop="gender" label="性别" width="120">
          <template slot-scope="scope">
            <el-tag effect="dark" v-if="scope.row.gender == 0">男</el-tag>
            <el-tag effect="dark" type="success" v-if="scope.row.gender == 1">女</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="telPhone" label="手机号" width="200"></el-table-column>
        <el-table-column prop="fullName" label="班级名称"></el-table-column>
        <el-table-column prop="status" label="状态" width="180">
          <template slot-scope="scope">
            <el-tag effect="dark" v-if="scope.row.status == 0">正常</el-tag>
            <el-tag effect="dark" type="warning" v-if="scope.row.status == 1">转学</el-tag>
            <el-tag effect="dark" type="danger" v-if="scope.row.status == 2">休学</el-tag>
            <el-tag effect="dark" type="danger" v-if="scope.row.status == 9">历史</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reportStatus" label="登记状态" width="180">
          <template slot-scope="scope">
            <el-tag effect="dark" type="warning" v-if="scope.row.reportStatus == 1">登记</el-tag>
            <el-tag effect="dark" v-else>未登记</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-view" @click="infoView(scope.row.id)">详情</el-button>
            <el-button v-if="permissions.admin_student_edit" type="text" icon="el-icon-edit" @click="addOrUpdateHandle(scope.row.id,'edit')">编辑</el-button>
<!--            <el-button v-if="permissions.admin_student_del" type="text" icon="el-icon-delete" @click="deleteHandle(scope.row)">删除</el-button>-->
          </template>
        </el-table-column>

      </el-table>

      <div class="avue-crud__pagination" style="margin-bottom: 25px;">
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100, 200]"
          :page-size="pageSize"
          :total="totalPage"
          background
          layout="total, sizes, prev, pager, next">
        </el-pagination>
      </div>
      <!-- 弹窗, 新增 / 修改 -->
      <table-form v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></table-form>
      <medical-report v-if="medicalReportVisible" ref="medicalReport" ></medical-report>
      <!-- 弹窗, 导入excel -->
      <excel-import v-if="excelVisible" ref="excelDialog" :fromYear="dataForm.fromYear" :toYear="dataForm.toYear"></excel-import>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { filterParams } from '@/util/tools'
import { remote } from '@/api/admin/dict'
import { getListByParentId } from '@/api/admin/region'
import { fetchList, delObj,printStudent,printOneStudent } from '@/api/pvm/student'
import { getSchoolList , getClassOptions,getSchoolListBySchoolType } from '@/api/pvm/school'
import {getGradeBySchoolId} from '@/api/pvm/grade'

import TableForm from './studentmedicalreport-form'
import ExcelImport from './ExcelImport'
import MedicalReport from './medicalreportview'
import {getOptometryListExport} from "@/api/pvm/pvmmedicalreport";

export default {
  name: 'pvmstudent',
  data() {
    return {
      searchFormShow: true,
      dataList: [],
      dataListLoading: false,
      pageIndex: 1,
      pageSize: 100,
      totalPage: 0,
      dataForm: {},
      provinceOptions: [],
      cityOptions: [],
      areaOptions: [],
      typeOptions: [],
      schoolOptions: [],
      gradeOptions: [],
      classOptions: [],
      statusOptions: [],
      addOrUpdateVisible: false,
      excelVisible: false,
      medicalReportVisible: false
    }
  },
  components: {
    TableForm,
    ExcelImport,
    MedicalReport
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  created() {
    this.$set(this.dataForm,'schoolType',0)
    this.getProvinceOptions()
    this.getSchoolTypeList()
    this.getSchoolOptions()
    this.getStudentStatus()
    this.searchHandle()
  },
  methods: {
    // 查询数据
    searchHandle(){
      //console.log(this.dataForm.fromYear)
      this.pageIndex = 1
      this.getDataList()
    },
    // 清空查询表单
    clearSearchForm(){
      for(let key in this.dataForm){
        this.dataForm[key] = ''
      }
    },
    // 获取数据列表
    getDataList(){
      let params1 = {current: this.pageIndex,size: this.pageSize}
      let params2 = filterParams(this.dataForm)
      this.dataListLoading = true
      fetchList(Object.assign(params1,params2)).then(response => {
        if(response.data.code == '0'){
          this.dataList = response.data.data.records
          this.totalPage = response.data.data.total
        }else{
          this.$message.error(response.data.msg)
        }
        this.dataListLoading = false
      })
    },
    // 每页条数改变
    sizeChangeHandle(val){
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页改变
    currentChangeHandle(val){
      this.pageIndex = val
      this.getDataList()
    },
    // 打开弹窗 新增 / 修改 / 详情
    addOrUpdateHandle(id,type){
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id,type)
      })
    },
    // 详情
    infoView(id,type){
      this.medicalReportVisible = true
      this.$nextTick(() => {
        this.$refs.medicalReport.init(id)
      })
    },
    // 删除教师
    deleteHandle(row){
      this.$confirm('此操作将永久删除该学生(学生名为:' + row.studentName + '), 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delObj(row.id)
      }).then(response => {
        if(response.data.code == '0'){
          this.$message.success('删除成功')
          this.getDataList()
        }else{
          this.$message.error(response.data.msg)
        }
      })
    },
    // 获取省级地址列表
    getProvinceOptions(){
      var parentId = '86';
      getListByParentId(parentId).then(response => {
        if(response.data.code == '0'){
          this.provinceOptions = response.data.data
        }else{
          this.$message.error(response.data.msg)
        }
      }).catch(() => {
        alert("省级地址出错了，请联系管理员a ")
      });
    },
    // 获取市级地址列表
    getCityOptions(val){
      this.cityOptions = []
      this.areaOptions = []
      this.$set(this.dataForm,'cityCode','')
      this.$set(this.dataForm,'areaCode','')
      if(val){
        getListByParentId(val).then(response => {
          if(response.data.code == '0'){
            this.cityOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        }).catch(() => {
          alert("市级地址出错了，请联系管理员a ")
        });
      }
    },
    // 获取区/县级地址列表
    getAreaOptions(val){
      this.areaOptions = []
      this.$set(this.dataForm,'areaCode','')
      if(val){
        getListByParentId(val).then(response => {
          if(response.data.code == '0'){
            this.areaOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        }).catch(() => {
          alert("市级地址出错了，请联系管理员a ")
        });
      }
    },
    // 获取学校类型列表
    getSchoolTypeList(){
      remote('school_type').then(response => {
        let responseData = response.data.data
        let list = []
        responseData.forEach(item => {
          list.push({label: item.label, value: item.value*1})
        })
        this.typeOptions = list
      })
    },
    printInfo(){
      let params = filterParams(this.dataForm)
      getOptometryListExport(params).then(response => {
          var blob = new Blob([response.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          });
          var reader = new FileReader();
          reader.readAsDataURL(blob);
          reader.onload = function(e) {
            var a = document.createElement('a');
            a.download = "学生体检信息.xlsx";
            a.href = URL.createObjectURL(blob);
            a.click();
          }
      })
    },
    schoolTypeChangeHandle(val){
      this.getSchoolOptions()
    },
    // 获取学校列表
    getSchoolOptions(data){
      getSchoolListBySchoolType(this.dataForm.schoolType).then(response => {
        if(response.data.code == '0'){
          this.schoolOptions = response.data.data
        }else{
          this.$message.error(response.data.msg)
        }
      })
    },
    // 获取年纪列表
    getGradeOption(schoolId){
      this.gradeOptions = []
      this.classOptions = []
      this.$set(this.dataForm,'gradeId','')
      this.$set(this.dataForm,'classId','')
      getGradeBySchoolId(schoolId).then(response => {
        if(response.data.code == '0'){
          this.gradeOptions = response.data.data
        }else{
          this.$message.error(response.data.msg)
        }
      })
    },
    // 获取班级列表
    getClassOption(gradeId){
      this.classOptions = []
      this.$set(this.dataForm,'classId','')
      getClassOptions(this.dataForm.schoolId,gradeId).then(response => {
        if(response.data.code == '0'){
          this.classOptions = response.data.data
        }else{
          this.$message.error(response.data.msg)
        }
      })
    },
    // 获取学生状态列表
    getStudentStatus(){
      remote('student_status').then(response => {
        let responseData = response.data.data
        let list = []
        responseData.forEach(item => {
          list.push({label: item.label, value: item.value*1})
        })
        this.statusOptions = list
      })
    },
    //  转换类型格式
    statusFormat(val){
      let obj = {}
      obj = this.typeOptions.find(item => {
        if(item.value === val){
          return item
        }
      })
      if(obj && obj.label){
        return obj.label
      }
    },
    importExcel(){
      if(this.dataForm.fromYear && this.dataForm.toYear){
        this.excelVisible = true
        this.$nextTick(() => {
          this.$refs.excelDialog.init()
        })
      }else{
        this.$message.warning('请选择学年')
      }
    },
    printStudent(){
      printStudent(Object.assign(this.dataForm)).then(response => {
          var blob = new Blob([response.data], {
            type: 'application/pdf;chartset=UTF-8'
          });
          var reader = new FileReader();
          reader.readAsDataURL(blob);
          reader.onload = function(e) {
            var a = document.createElement('a');
            a.download = "学生空白表.pdf";
            a.href = URL.createObjectURL(blob);
            a.click();
          }
      })
    }
  }
}
</script>
